﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using NPSoft.Ferrero.Framework.Crosscutting;
using NPSoft.Ferrero.Framework.Utility;

namespace NPSoft.Ferrero.DataBridge.BLL
{
    public class FCR_IN_MailServices : IFCR_IN_MailServices
    {
        private const string SAP = "global SAP";
        private const string FC = "Forecast";
        private const string WCN = "WinChannel";

        private const string DIST = "Distributor";
        private const string EMP = "Employee";
        private const string PRD = "Product";
        private const string UOM = "UOM";
        private const string PRD_PRICE = "Product Price";
        private const string INV = "Inventory";
        private const string UNMAPPED = "Unmapped Store";
        private const string MAPPED = "Mapped Store";
        private const string EX_F = "Ex_F After DC";
        private const string EX_F_T = "Ex_F Target";


        private string subjectTemplate = "[{0}] {1} {2} Interface On {3}";
        private string errTemplate = @"Dear Team,</BR>
                            Totally {0} {1} information record(s) received 
                            from {2} interface: {3} record(s) imported into local IT system successfully, 
                            {4} record(s) imported unsuccessfully.";
        private string rgtTemplate = @"Dear Team,</BR>
                            Totally {0} {1} information record(s) received 
                            from {2} interface: {3} record(s) imported into local IT system successfully.";

        private string fileNotFoundTemplate = @"Dear Team,</BR>
                            There is no file in FTP folder.";


        /// <summary>
        /// 
        /// </summary>
        private enum ExecErrorType
        {
            Standard = 0,
            FileNotFound = 1
        }

        public int ID { get; set; }

        public int ErrorType { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <param name="strTos"></param>
        /// <param name="strCcs"></param>
        /// <param name="identifier"></param>
        /// <param name="errorType"></param>
        /// <returns></returns>
        [UserLog]
        public string SendMail(string account, string password, List<string> strTos, List<string> strCcs)
        {
            NPMessage result = new NPMessage();
            List<MailAddress> tos = new List<MailAddress>();
            List<MailAddress> ccs = new List<MailAddress>();
            MailHelper mail = new MailHelper();
            MailMessage msg = new MailMessage();

            string str = string.Empty;
            string bodyMsg = string.Empty;
            string src = string.Empty;
            string dtNow = DateTime.Now.ToString("yyyy-MM-dd");

            BusinessIdentifier bid = BusinessIdentifier.NONE;
            string businessName = string.Empty;

            // 设置邮箱及发件人信息
            mail.Account = account;
            mail.Password = password;
            msg.From = new MailAddress(mail.Account, "FerreroAzure");

            #region "设置收件人信息"

            foreach (string to in strTos)
            {
                if (!string.IsNullOrEmpty(to))
                {
                    // To Address Validation
                    if (!NPValidator.IsEmail(to))
                    {
                        result.Success = false;
                        result.Add("收件人地址无法识别为有效的邮箱地址！");
                    }
                    else
                    {
                        tos.Add(new MailAddress(to));
                    };
                }
            }

            foreach (string cc in strCcs)
            {
                // CC Address Validation
                if (!string.IsNullOrEmpty(cc) && !NPValidator.IsEmail(cc))
                {
                    result.Success = false;
                    result.Add("抄送地址无法识别为有效的邮箱地址！");
                }
                else if (!string.IsNullOrEmpty(cc))
                {
                    ccs.Add(new MailAddress(cc));
                };
            }

            #endregion

            try
            {
                #region 业务标识处理
                if (Enum.TryParse<BusinessIdentifier>(this.ID.ToString(), out bid))
                {
                    switch (bid)
                    {
                        case BusinessIdentifier.Distributor:
                            businessName = DIST;
                            src = SAP;
                            break;
                        case BusinessIdentifier.Employee:
                            businessName = EMP;
                            src = SAP;
                            break;
                        case BusinessIdentifier.EmployeeCN30:
                            businessName = EMP;
                            src = SAP;
                            break;
                        case BusinessIdentifier.Product:
                            businessName = PRD;
                            src = SAP;
                            break;
                        case BusinessIdentifier.UOM:
                            businessName = UOM;
                            src = SAP;
                            break;
                        case BusinessIdentifier.ProductCostPrice:
                            businessName = PRD_PRICE;
                            src = SAP;
                            break;
                        case BusinessIdentifier.Unmapped_Stores:
                            businessName = UNMAPPED;
                            src = WCN;
                            break;
                        case BusinessIdentifier.Mapped_Stores:
                            businessName = MAPPED;
                            src = WCN;
                            break;
                        case BusinessIdentifier.EX_F:
                            businessName = EX_F;
                            src = SAP;
                            break;
                        case BusinessIdentifier.EX_F_TARGET:
                            businessName = EX_F_T;
                            src = FC;
                            break;
                    }
                }
                else
                {
                    result.Success = false;
                    result.Add("不明确的业务标识符！");
                }

                #endregion

                if (result.Success)
                {
                    #region 获取当日处理结果

                    DataTable dt_right = this.GetRightData(bid);
                    DataTable dt_total = this.GetTotalData(bid);
                    DataTable dt_error = this.GetErrorData(bid);
                    DataTable dt_err_msg = this.GetErrorMsgData(bid);
                    int rightcnt = 0;
                    int totalcnt = 0;
                    int errorcnt = 0;
                    if (dt_right.Rows.Count > 0)
                    {
                        int.TryParse(dt_right.Rows[0]["CNT"].ToString(), out rightcnt);
                    }
                    if (dt_total.Rows.Count > 0)
                    {
                        int.TryParse(dt_total.Rows[0]["CNT"].ToString(), out totalcnt);
                    }
                    if (dt_error.Rows.Count > 0)
                    {
                        int.TryParse(dt_error.Rows[0]["CNT"].ToString(), out errorcnt);
                    }
                    #endregion

                    #region 邮件正文及附件处理

                    ExecErrorType eet = ExecErrorType.Standard;
                    if (Enum.TryParse<ExecErrorType>(this.ErrorType.ToString(), out eet))
                    {
                        switch (eet)
                        {
                            case ExecErrorType.Standard:
                                // 没错误不发附件
                                if (dt_err_msg.Rows.Count > 0)
                                {
                                    msg.Subject = string.Format(subjectTemplate, "Failed", src, businessName,dtNow);
                                    bodyMsg = string.Format(errTemplate, totalcnt, businessName, src, rightcnt, errorcnt);
                                    byte[] bys = mail.GetAttachStream(dt_err_msg);
                                    if (bys != null && bys.Length > 0)
                                    {
                                        MemoryStream ms = new MemoryStream(bys);
                                        Attachment at = new Attachment(ms, "ErrorMsg.xlsx", MediaTypeNames.Text.Plain);
                                        msg.Attachments.Add(at);
                                    }
                                }
                                else
                                {
                                    msg.Subject = string.Format(subjectTemplate, "Succeeded", src, businessName, dtNow);
                                    bodyMsg = string.Format(rgtTemplate, totalcnt, businessName, src, rightcnt);
                                    if ((businessName == EMP || businessName == PRD_PRICE))
                                    {
                                        if (totalcnt == 0)
                                        {
                                            msg.Subject = string.Format(subjectTemplate, "Failed", src, businessName,dtNow);
                                            bodyMsg = string.Format(errTemplate, totalcnt, businessName, src, rightcnt, errorcnt);
                                        }
                                    }
                                }
                                break;
                            case ExecErrorType.FileNotFound:
                                msg.Subject = string.Format(subjectTemplate, "Failed", src, businessName,dtNow);
                                bodyMsg = fileNotFoundTemplate;
                                break;
                        }
                    }

                    #endregion

                    msg.Body = bodyMsg;
                    result = mail.SendBySMTP(tos, ccs, msg);

                    msg.Attachments.Dispose();
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Add(ex.Message);
            }

            return result.Message;
        }

        /// <summary>
        /// 获取正确数据
        /// </summary>
        /// <param name="id">业务标识</param>
        /// <returns>正确的数据</returns>
        public DataTable GetRightData(BusinessIdentifier id)
        {
            GetResultData bll = new GetResultData();
            DataTable dt_right = new DataTable();
            dt_right = bll.GetInSuccessData(id);
            return dt_right;
        }

        /// <summary>
        /// 获取增量数据
        /// </summary>
        /// <param name="id">业务标识</param>
        /// <returns>增量的数据</returns>
        public DataTable GetTotalData(BusinessIdentifier id)
        {
            GetResultData bll = new GetResultData();
            DataTable dt_total = new DataTable();
            dt_total = bll.GetInTotalData(id);
            return dt_total;
        }

        /// <summary>
        /// 获取错误数据
        /// </summary>
        /// <param name="id">业务标识</param>
        /// <returns>错误的数据</returns>
        public DataTable GetErrorData(BusinessIdentifier id)
        {
            GetResultData bll = new GetResultData();
            DataTable dt_error = new DataTable();
            dt_error = bll.GetInErrorData(id);
            return dt_error;
        }

        /// <summary>
        /// 获取错误信息数据
        /// </summary>
        /// <param name="id">业务标识</param>
        /// <returns>错误信息的数据</returns>
        public DataTable GetErrorMsgData(BusinessIdentifier id)
        {
            GetResultData bll = new GetResultData();
            DataTable dt_err_msg = bll.GetInErrorMsgData(id);
            return dt_err_msg;
        }
    }
}
